package com.googlecode.mysqlcommenter.model;

import java.util.ArrayList;
import java.util.List;

import javax.swing.event.TreeModelEvent;
import javax.swing.event.TreeModelListener;
import javax.swing.tree.TreeModel;
import javax.swing.tree.TreePath;

public class ConnTreeModel extends AbstractDbItem  implements TreeModel{

   public ConnTreeModel(String name) {
      super(name);
   }

   private List<Db> dbs = new ArrayList<Db>();
   private List<TreeModelListener> listeners = new ArrayList<TreeModelListener>();

   public void addTreeModelListener(TreeModelListener l) {
      listeners.add(l);
   }

   public Object getChild(Object parent, int index) {

      if (parent instanceof Table){
         return ((Table)parent).getColumns().get(index);
      }
      if (parent instanceof Db){
         return ((Db)parent).getTables().get(index);
      }

      return dbs.get(index);
   }

   public int getChildCount(Object parent) {
      if (parent instanceof Table){
         return ((Table)parent).getColumns().size();
      }
      if (parent instanceof Db){
         return ((Db)parent).getTables().size();
      }
      return dbs.size();
   }

   public int getIndexOfChild(Object parent, Object child) {
      if (parent instanceof Table){
         return ((Table)parent).getColumns().indexOf(child);
      }
      if (parent instanceof Db){
         return ((Db)parent).getTables().indexOf(child);
      }
      return dbs.indexOf(child);
   }

   public Object getRoot() {
      return this;
   }

   public boolean isLeaf(Object node) {
      return node instanceof Column;
   }

   public void removeTreeModelListener(TreeModelListener l) {
      listeners.remove(l);
   }

   public void valueForPathChanged(TreePath path, Object newValue) {
      // TODO Auto-generated method stub

   }

   public List<Db> getDbs() {
      return dbs;
   }

   public void setDbs(List<Db> dbs) {
      this.dbs = dbs;
      for (TreeModelListener l : listeners) {
         l.treeNodesInserted(new TreeModelEvent(this,new Object[]{this}));
      }
   }

   @Override
   public Db getDb() {
      return null;
   }


}
